package com.tensquare.article.interceptor;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.tensquare.entity.Result;
import com.tensquare.entity.StatusCode;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserAuthRestInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean flag = false;

        if (!(handler instanceof HandlerMethod)){
            return true;
        }

        System.out.println(request.getHeader("Content-Type"));
//        if (!request.getHeader("Content-Type").equals(MediaType.APPLICATION_JSON_VALUE)){
//            flag = true;
//        }

        if (!checkIsAccessGateway(request,response)) {
            //未经过网关直接访问项目解密出错
            response.setContentType("text/html;charset=utf-8");
            ObjectMapper objectMapper = new ObjectMapper();
            Result result = new Result(true, "请求错误", StatusCode.ACCESSERROR);
            response.setStatus(HttpStatus.ACCEPTED.value());
            String value = objectMapper.writeValueAsString(result);
            response.getWriter().write(value);
            return false;
        }
        return super.preHandle(request, response, handler);
    }

    public boolean checkIsAccessGateway(HttpServletRequest request, HttpServletResponse response){
        boolean flag = false;
        String is_after_gateway = request.getHeader("IS_AFTER_GATEWAY");
        if ("Y".equals(is_after_gateway)){
            flag = true;
        }
        return flag;
    }
}
